from django import forms
from django.contrib.auth.models import User


class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=50)
    email = forms.EmailField()
    password = forms.CharField(max_length=100, min_length=6, widget=forms.PasswordInput,error_messages={
        "min_length": "密码长度不能小于6位",
        "max_length": "密码长度不能大于100位",
        "required": "密码不能为空",

    })
    re_password = forms.CharField(max_length=100, min_length=6, widget=forms.PasswordInput)
    # def clean_re_password(self):
    #
    #     password = self.cleaned_data.get("password")
    #     re_password = self.cleaned_data.get("re_password")
    #     if password != re_password:
    #         self.add_error("re_password", "两次密码不一致.")
    #     return re_password

    def clean(self):
        password = self.cleaned_data.get("password")
        re_password = self.cleaned_data.get("re_password")
        if password!= re_password:
            self.add_error("re_password", "两次密码不一致.")
        return self.cleaned_data


    def clean_username(self):
        username = self.cleaned_data.get("username")
        if User.objects.filter(username=username).exists():
            self.add_error("username", "用户被占用.")
        return username

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if User.objects.filter(email=email).exists():
            self.add_error("email", "邮箱被占用.")
        return email